var express = require("express");
var app = express();
var bodyParse = require("body-parser");
let fs = require("fs");
const os = require("os");
const { exec } = require("child_process");
const { log } = require("console");
app.all("*", function (req, res, next) {

    res.header("Access-Control-Allow-Origin", "*"); //允许源访问，本利前端访问路径为“http://localhost:8080”
    res.header(
        "Access-Control-Allow-Headers",
        "Content-Type,Content-Length, Authorization, Accept,X-Requested-With"
    );
    res.header("Access-Control-Allow-Methods", "PUT,POST,GET,DELETE,OPTIONS");
    res.header("Access-Control-Allow-Credentials", true);
    res.header("X-Powered-By", " 3.2.1");
    next();
});
app.use(bodyParse.urlencoded({ extended: true }));
app.use(bodyParse.json());
app.use(bodyParse.text({ limit: "10Mb" }));
app.get("/", function (req, res) {});

var onlineUser = "0 人";
var dangerWarning = "0";
var waiting = "0";
//user数组
var userList = [
  {
    acct: "123456",
    pwd: "654321",
    id: "0",

    company: "心动健康管理员",
    username: "李白",
    email: "123456789@qq.com",
    firstName: "212121",
    lastName: "数据监控员",
    address: "南山敬老院, 某地, 中国",
    city: "数据监控小组1组",
    postalCode: "132154",
    country: "12345678910",
    aboutMe: `愿天下心诚剑士人人可剑开天门!`,
  },
];

function findUser(acct, pwd) {
  for (var i = 0; i < userList.length; i++) {
    if (acct == userList[i].acct) {
      if (pwd == userList[i].pwd) {
        return i;
      }
    }
  }
  return -1;
}
app.post("/stats", function (req, res) {
  //登录
  //获取登录名称和密码
  var acct = req.body.acct;
  var pwd = req.body.pwd;
  //向前台反馈信息

  var flag = findUser(acct, pwd);

  if (flag != -1) {
    var loginMsg = {
      statu: "OK",
      company: userList[flag].company,
      username: userList[flag].username,
      email: userList[flag].email,
      firstName: userList[flag].firstName,
      lastName: userList[flag].lastName,
      address: userList[flag].address,
      city: userList[flag].city,
      postalCode: userList[flag].postalCode,
      country: userList[flag].country,
      aboutMe: userList[flag].aboutMe,
    };
    var logoutMsg = { statu: "NO" };
    loginMsg = JSON.stringify(loginMsg);
    res.status(200).send(loginMsg);
  } else {
    res.status(200).send(logoutMsg);
  }
});
app.post("/stats/reg", function (req, res) {
  var acct1 = req.body.acct;
  var pwd1 = req.body.pwd;
  var id1 = userList.length.toString();
  var company1 = req.body.company;
  var username1 = req.body.username;
  var email1 = req.body.email;
  var firstName1 = req.body.firstName;
  var lastName1 = req.body.lastName;
  var address1 = req.body.address;
  var city1 = req.body.city;
  var postalCode1 = req.body.postalCode;
  var country1 = req.body.country;
  var aboutMe1 = req.body.aboutMe;
  var addUser = {
    acct: acct1,
    pwd: pwd1,
    id: id1,
    company: company1,
    username: username1,
    email: email1,
    firstName: firstName1,
    lastName: lastName1,
    address: address1,
    city: city1,
    postalCode: postalCode1,
    country: country1,
    aboutMe: aboutMe1,
  };
  userList.push(addUser);
  var addUser2 = {
    statu: "OKR",
    company: company1,
    username: username1,
    email: email1,
    firstName: firstName1,
    lastName: lastName1,
    address: address1,
    city: city1,
    postalCode: postalCode1,
    country: country1,
    aboutMe: aboutMe1,
  };
  addUser = JSON.stringify(addUser2);
  res.status(200).send(addUser2);
});

app.post("/upd", function (req, res) {
  var upData = {
    fileSize: "1.0",
    fileNum: fileList.length,
    onlineNum: onlineUser,
    dangerWarn: dangerWarning,
    modelWait: waiting,
  };
  upData = JSON.stringify(upData);
  res.status(200).send(upData);
});

var usedPercent;
app.post("/watch", function (req, res) {
  var coreNum;
  var cpuModel = [];
  var cpuSpeed = [];
  var cpuPct = [];
  os.cpus().forEach((cpu, idx, arr) => {
    var times = cpu.times;
    console.log(`cpu${idx}：`);
    console.log(`型号：${cpu.model}`);
    console.log(`频率：${cpu.speed}MHz`);
    console.log(
      `使用率：${(
        (1 -
          times.idle /
            (times.idle + times.user + times.nice + times.sys + times.irq)) *
        100
      ).toFixed(2)}%`
    );
    coreNum = idx;
    cpuModel.push(cpu.model);
    cpuSpeed.push(cpu.speed);
    cpuPct.push(
      (
        (1 -
          times.idle /
            (times.idle + times.user + times.nice + times.sys + times.irq)) *
        100
      ).toFixed(2)
    );
  });

  // 获取内存使用率
  var dealMem = (mem) => {
    var G = 0,
      M = 0,
      KB = 0;
    mem > 1 << 30 && (G = (mem / (1 << 30)).toFixed(2));
    mem > 1 << 20 &&
      mem > 1 << 10 &&
      mem > 1 << 20 &&
      (KB = (mem / (1 << 10)).toFixed(2));
    return G > 0 ? G + "G" : M > 0 ? M + "M" : KB > 0 ? KB + "KB" : mem + "B";
  };

  var totalMem = os.totalmem(); //总内存
  var freeMem = os.freemem(); //空闲内存
  var memUsage = (totalMem - freeMem) / totalMem;
  console.log("Mem Usage:", memUsage);
  totalMem = dealMem(totalMem);
  freeMem = dealMem(freeMem);
  // 获取磁盘使用率
  exec("df -k", (err, stdout, stderr) => {
    if (err) {
      console.error(err);
      return;
    }
    const lines = stdout.split("\n");
    const [headerLine, dataLine] = lines.slice(0, 2);
    const [, , , usedStr, ,] = dataLine.split(/\s+/);
    usedPercent = parseFloat(usedStr) / 100;
  });

  const arch = os.arch();
  //操作系统内核
  const kernel = os.type();

  //操作系统平台
  const pf = os.platform();
  var dealTime = (seconds) => {
    seconds = seconds | 0;
    var day = (seconds / (3600 * 24)) | 0;
    var hours = ((seconds - day * 3600) / 3600) | 0;
    var minutes = ((seconds - day * 3600 * 24 - hours * 3600) / 60) | 0;
    var second = seconds % 60;
    day < 10 && (day = "0" + day);
    hours < 10 && (hours = "0" + hours);
    minutes < 10 && (minutes = "0" + minutes);
    second < 10 && (second = "0" + second);
    return [day, hours, minutes, second].join(":");
  };
  //系统开机时间
  const uptime = os.uptime();
  var tm = dealTime(uptime);
  console.log("开机时间：" + tm);
  var useMsg = {
    CPUNUM: coreNum,
    CPUMOD: cpuModel,
    CPUHZ: cpuSpeed,
    CPUUSE: cpuPct,
    CPUARCH: arch,
    MEMTOT: totalMem,
    MEMFRE: freeMem,
    MEMPCT: memUsage,
    DSKPCT: usedPercent,
    OSCORE: kernel,
    PF: pf,
    TIME: tm,
  };
  useMsg = JSON.stringify(useMsg);
  res.status(200).send(useMsg);
});
var phoneUser = [
  {
    id: 0,
    UUID: "123456789",
    stairP0: 50,
    stairP1: 20,
    stairP2: 10,
    walkP0: 20,
    walkP1: 10,
    walkP2: 50,
    runP0: 30,
    runP1: 70,
    runP2: 40,
    sitP0: 0,
    sitP1: 0,
    sitP2: 0,
    playP0: 0,
    playP1: 0,
    playP2: 0,
    lieP0: 0,
    lieP1: 0,
    lieP2: 0,
    sad0: 30,
    sad1: 60,
    sad2: 90,
    calm0: 30,
    calm1: 20,
    calm2: 5,
    angry0: 10,
    angry1: 10,
    angry2: 5,
    happy0: 30,
    happy1: 10,
    happy2: 0,
    fileNum: 0,
  },
];
function findPhoneUser(findUUID) {
  for (var i = 0; i < phoneUser.length; i++) {
    if (phoneUser[i].UUID == findUUID) {
      return phoneUser[i].id;
    }
  }
  return -1;
}
function findFeedbackUser(findID) {
  for (var i = 0; i < feedback.length; i++) {
    if (feedback[i].id == findID) {
      return i;
    }
  }
  return -1;
}
var feedback = [
  {
    id: 0,
    stairP: 0,
    walkP: 0,
    runP: 0,
    sitP: 0,
    playP: 0,
    lieP: 0,
    sad: 0,
    calm: 0,
    angry: 0,
    happy: 0,
  },
];
app.post("/opt", function (req, res) {
  var UUID = req.get("UUID");
  console.log("111");
  var fdIdx = -1;
  var nowID = findPhoneUser(UUID);
  if (nowID == -1) {
    phoneUser.push({
      id: phoneUser.length,
      UUID: UUID,
      stairP0: 100,
      stairP1: 100,
      stairP2: 100,
      walkP0: 0,
      walkP1: 0,
      walkP2: 0,
      runP0: 0,
      runP1: 0,
      runP2: 0,
      sitP0: 0,
      sitP1: 0,
      sitP2: 0,
      playP0: 0,
      playP1: 0,
      playP2: 0,
      lieP0: 0,
      lieP1: 0,
      lieP2: 0,
      sad0: 0,
      sad1: 0,
      sad2: 0,
      calm0: 0,
      calm1: 0,
      calm2: 0,
      angry0: 0,
      angry1: 0,
      angry2: 0,
      happy0: 0,
      happy1: 0,
      happy2: 0,
      fileNum: 0,
    });
  } else {
    if (req.header.opt == "1") {
      fdIdx = findFeedbackUser(nowID);
      if (fdIdx == -1) {
        feedback.push({
          id: nowID,
          stairP: 0,
          walkP: 0,
          runP: 0,
          sitP: 0,
          playP: 0,
          lieP: 0,
          sad: 1,
          calm: 0,
          angry: 0,
          happy: 0,
        });
      } else {
        feedback[fdIdx].sad += feedback[fdIdx].sad + 1;
      }
    } else if (req.header.opt == "2") {
      if (fdIdx == -1) {
        feedback.push({
          id: nowID,
          stairP: 0,
          walkP: 0,
          runP: 0,
          sitP: 0,
          playP: 0,
          lieP: 0,
          sad: 0,
          calm: 1,
          angry: 0,
          happy: 0,
        });
      } else {
        feedback[fdIdx].calm += feedback[fdIdx].calm + 1;
      }
    } else if (req.header.opt == "3") {
      if (fdIdx == -1) {
        feedback.push({
          id: nowID,
          stairP: 0,
          walkP: 0,
          runP: 0,
          sitP: 0,
          playP: 0,
          lieP: 0,
          sad: 0,
          calm: 0,
          angry: 1,
          happy: 0,
        });
      } else {
        feedback[fdIdx].angry += feedback[fdIdx].angry + 1;
      }
    } else if (req.header.opt == "4") {
      if (fdIdx == -1) {
        feedback.push({
          id: nowID,
          stairP: 0,
          walkP: 0,
          runP: 0,
          sitP: 0,
          playP: 0,
          lieP: 0,
          sad: 0,
          calm: 0,
          angry: 0,
          happy: 1,
        });
      } else {
        feedback[fdIdx].happy += feedback[fdIdx].happy + 1;
      }
    }

}

})


//const execpy = require('child_process').exec

app.post("/file", (req, res) => {
  console.log("已收到" + __dirname);
  var UUID = req.get("UUID");
  var nowID = findPhoneUser(UUID);

  var fileName = req.get("fn");
  var path = __dirname + "/file/" + req.get("UUID") + "/";

  console.log("已收到" + path);
  if (!fs.existsSync(__dirname + "/file/")) {
    fs.mkdir(__dirname + "/file/", (err) => {
      log(err);
    });
    if (!fs.existsSync(__dirname + "/file/" + req.get("UUID"))) {
      fs.mkdir(__dirname + "/file/" + req.get("UUID"), (err) => {
        log(err);
      });
    }
    else{
        fs.mkdir(path,(err)=>{log(err)})
        fs.writeFile(path+fileName,req.body,(err)=>{log(err)})
        console.log("文件已保存"+path)
    }
    if (nowID == -1) {
        phoneUser.push({
            id: phoneUser.length,
            UUID:UUID,
            stairP0: 100, stairP1: 100, stairP2: 100,
            walkP0: 0, walkP1: 0, walkP2: 0,
            runP0: 0, runP1: 0, runP2: 0, sitP0: 0, sitP1: 0, sitP2: 0,
            playP0: 0, playP1: 0, playP2: 0,
            lieP0: 0, lieP1: 0, lieP2: 0,
            sad0: 0, sad1: 0, sad2: 0,
            calm0: 0, calm1: 0, calm2: 0,
            angry0: 0, angry1: 0, angry2: 0,
            happy0: 0, happy1: 0, happy2: 0,
            fileNum: 1
        })
       
    } 
    
/*

    const p0 = new Promise((resolve, reject)=>{
        let v0 = "i am js"
        resolve(v0)
    })
    p0.then((value)=>{
        console.log(value)
    }).then(()=>{
        let cmdStr = 'python3 LTSM.py'
        execpy(cmdStr, (err, stdout, stderr)=>{
            if(err){
                console.log(stderr)
            }else{
                //fs.readFile("")
            }
        })
    }).catch((err)=>{
        console.log(err)
    }).finally(()=>{
        
    })*/
  }
})



app.post("/trend", (req, res) => {
  var type = req.get("type");
  var UUID = req.get("UUID");
  var nowID = findPhoneUser(UUID);
  if (nowID == -1) {
    phoneUser.push({
      id: phoneUser.length,
      UUID: UUID,
      stairP0: 50,
      stairP1: 100,
      stairP2: 100,
      walkP0: 4,
      walkP1: 0,
      walkP2: 0,
      runP0: 0,
      runP1: 0,
      runP2: 0,
      sitP0: 0,
      sitP1: 0,
      sitP2: 0,
      playP0: 6,
      playP1: 0,
      playP2: 0,
      lieP0: 20,
      lieP1: 0,
      lieP2: 0,
      sad0: 20,
      sad1: 0,
      sad2: 0,
      calm0: 0,
      calm1: 0,
      calm2: 0,
      angry0: 0,
      angry1: 0,
      angry2: 0,
      happy0: 0,
      happy1: 0,
      happy2: 0,
      fileNum: 0,
    });
    nowID = phoneUser.length - 1;
  }
  if (type == "act") {
    res
      .status(200)
      .send(
        `${phoneUser[nowID].stairP0},${phoneUser[nowID].walkP0},${phoneUser[nowID].runP0},${phoneUser[nowID].sitP0},${phoneUser[nowID].playP0},${phoneUser[nowID].lieP0}`
      );
  }
});

app.set("view engine", "ejs");
app.use(express.static("./public"));
app.get("/examStart", (req, res) => {
  res.render("examFormFeeling");
});
var server = app.listen(3000);
